<template>
  <div class="code-block-wrapper">
    <div class="code-block-header">
      <span class="code-lang">{{ language }}</span>
      <el-button
        size="small"
        type="text"
        @click="copyCode"
      >
        <el-icon><DocumentCopy /></el-icon>
        复制
      </el-button>
    </div>
    <pre class="code-block"><code>{{ code }}</code></pre>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'

const props = defineProps({
  code: {
    type: String,
    required: true
  },
  language: {
    type: String,
    default: 'text'
  }
})

const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(props.code)
    ElMessage.success('代码已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}
</script>

<style scoped>
.code-block-wrapper {
  margin: 15px 0;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  background-color: #fafafa;
}

.code-block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.code-lang {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.code-block {
  margin: 0;
  padding: 16px;
  background-color: #282c34;
  color: #abb2bf;
  overflow-x: auto;
  font-family: 'Courier New', 'Consolas', 'Monaco', monospace;
  font-size: 14px;
  line-height: 1.6;
}

.code-block code {
  color: #abb2bf;
  background: transparent;
  padding: 0;
  white-space: pre;
}
</style>

